import { Canvas, useThree } from "@react-three/fiber";
import {
  CameraControls,
  Center,
  Html,
  OrbitControls,
  Text,
  Text3D,
  TransformControls,
  useProgress,
  useAnimations,
  useGLTF,
} from "@react-three/drei";
import { useFrame } from "@react-three/fiber";
import Lights from "./Lights.jsx";
import { AnimationMixer, Vector3 } from "three";
import { useEffect, useMemo, useRef, useState } from "react";
import React from "react";
import { Modal } from "antd";
import { Suspense } from "react";

function CreateWareHouse() {
  const warehouse = useGLTF("./warehouse.glb");
  const { actions } = useAnimations(warehouse.animations, warehouse.scene);
  useEffect(() => {
    actions.scroll.play();
  }, []);

  const body = useRef();

  const [smoothedCameraPosition, setSmoothedCameraPosition] = useState(
    new Vector3(5, 2, 0)
  );
  const [smoothedCameraTarget, setSmoothedCameraTarget] = useState(
    new Vector3(0, 0, 0)
  );

  warehouse.scene.children.forEach((mesh) => {
    mesh.castShadow = true;
    mesh.receiveShadow = true;
  });

  let clickPosition = new Vector3(4, 1, 0);
  let lookFlag = false;

  useFrame((state, delta) => {
    if (lookFlag) {
      // 移动摄像头
      const cameraPosition = new Vector3();
      cameraPosition.copy(clickPosition);
      if (state.camera.position.x > cameraPosition.x) {
        cameraPosition.x += 0.3;
      } else {
        cameraPosition.x -= 0.3;
      }

      cameraPosition.y += 0.1;

      const cameraTarget = new Vector3();
      cameraTarget.copy(clickPosition);

      // 平滑靠近
      // 平滑靠近
      setSmoothedCameraPosition((prev) => prev.lerp(cameraPosition, 5 * delta));
      setSmoothedCameraTarget((prev) => prev.lerp(cameraTarget, 5 * delta));

      state.camera.position.copy(smoothedCameraPosition);
      state.camera.lookAt(smoothedCameraTarget);
    }

    if (state.controls) {
      state.controls.target.copy(smoothedCameraTarget);
      setSmoothedCameraPosition(state.camera.position);
    }
  });

  const [isModalOpen, setIsModalOpen] = useState(false);
  const [info, setInfo] = useState({});

  const handleClick = (mesh) => {
    if (mesh.object.name !== "地面" && mesh.object.name != "球体") {
      clickPosition.copy(mesh.object.position);
      clickPosition.multiplyScalar(0.01);
      lookFlag = true;
      mesh.stopPropagation();
      // 模拟请求
      setTimeout(() => {
        setIsModalOpen(true);
        setInfo({
          name: mesh.object.name,
          articleId: Math.floor(Math.random() * 9999999),
          articleName: "奇奇怪怪的东西",
          addTime: new Date(),
        });
        lookFlag = false;
      }, 1000);
    }
  };

  return (
    <>
      <Html>
        <Modal
          title="库位信息"
          open={isModalOpen}
          onCancel={() => {
            setIsModalOpen(false);
          }}
          footer={[]}
        >
          <p>货架号：{info.name}</p>
          <p>物料编码：{info.articleId}</p>
          <p>物料名称：{info.articleName}</p>
          <p>入库时间：{info.addTime + ""}</p>
        </Modal>
      </Html>

      <color args={["skyblue"]} attach="background" />

      <Text3D
        font="./helvetiker_regular.typeface.json"
        size={0.2}
        position={[2, 0.01, 1]}
        rotation-y={Math.PI * 0.5}
        height={0.05}
        castShadow
      >
        Kevin Warehouse
        <meshBasicMaterial color={"blue"} />
      </Text3D>

      {lookFlag ? "" : <OrbitControls makeDefault />}
      <TransformControls>
        <primitive
          ref={body}
          object={warehouse.scene}
          scale={0.01}
          onClick={handleClick}
          receiveShadow
          castShadow
        />
      </TransformControls>
    </>
  );
}

function Loader() {
  const { progress } = useProgress();
  return (
    <Html center>
      <svg
        xmlns="http://www.w3.org/2000/svg"
        xmlnsXlink="http://www.w3.org/1999/xlink"
        style={{
          margin: "auto",
          background: "#fff",
          display: "block",
          backgroundColor: "transparent",
        }}
        width="150px"
        height="150px"
        viewBox="0 0 100 100"
        preserveAspectRatio="xMidYMid"
      >
        <g>
          <circle cx="60" cy="50" r="4" fill="#e15b64">
            <animate
              attributeName="cx"
              repeatCount="indefinite"
              dur="1s"
              values="95;35"
              keyTimes="0;1"
              begin="-0.67s"
            ></animate>
            <animate
              attributeName="fill-opacity"
              repeatCount="indefinite"
              dur="1s"
              values="0;1;1"
              keyTimes="0;0.2;1"
              begin="-0.67s"
            ></animate>
          </circle>
          <circle cx="60" cy="50" r="4" fill="#e15b64">
            <animate
              attributeName="cx"
              repeatCount="indefinite"
              dur="1s"
              values="95;35"
              keyTimes="0;1"
              begin="-0.33s"
            ></animate>
            <animate
              attributeName="fill-opacity"
              repeatCount="indefinite"
              dur="1s"
              values="0;1;1"
              keyTimes="0;0.2;1"
              begin="-0.33s"
            ></animate>
          </circle>
          <circle cx="60" cy="50" r="4" fill="#e15b64">
            <animate
              attributeName="cx"
              repeatCount="indefinite"
              dur="1s"
              values="95;35"
              keyTimes="0;1"
              begin="0s"
            ></animate>
            <animate
              attributeName="fill-opacity"
              repeatCount="indefinite"
              dur="1s"
              values="0;1;1"
              keyTimes="0;0.2;1"
              begin="0s"
            ></animate>
          </circle>
        </g>
        <g transform="translate(-15 0)">
          <path
            d="M50 50L20 50A30 30 0 0 0 80 50Z"
            fill="#f8b26a"
            transform="rotate(90 50 50)"
          ></path>
          <path d="M50 50L20 50A30 30 0 0 0 80 50Z" fill="#f8b26a">
            <animateTransform
              attributeName="transform"
              type="rotate"
              repeatCount="indefinite"
              dur="1s"
              values="0 50 50;45 50 50;0 50 50"
              keyTimes="0;0.5;1"
            ></animateTransform>
          </path>
          <path d="M50 50L20 50A30 30 0 0 1 80 50Z" fill="#f8b26a">
            <animateTransform
              attributeName="transform"
              type="rotate"
              repeatCount="indefinite"
              dur="1s"
              values="0 50 50;-45 50 50;0 50 50"
              keyTimes="0;0.5;1"
            ></animateTransform>
          </path>
        </g>
      </svg>
      <div
        style={{
          width: "150px",
        }}
      >
        {progress} % loaded
      </div>
    </Html>
  );
}

function App() {
  return (
    <Canvas
      shadows
      camera={{
        fov: 45,
        near: 0.1,
        far: 200,
        position: [5, 2, 0],
      }}
    >
      {/* <Loader /> */}
      <Suspense fallback={<Loader />}>
        <Lights />
        <CreateWareHouse />
      </Suspense>
    </Canvas>
  );
}

export default App;
